import en from './en.json'
import km from './km.json'
import {cache} from '@/js/s94_tool.js'


let messages = { en, km }

export const CACHE_KEY = 'cache_language_MSLXDv51a5Qom853'
export const LANG_MAP = {
  zh_cn: '中文简体',
  en: 'English',
  km: 'ខ្មែរ',
}

/**缓存语言包
 * @param {Object} data 语言包，格式：{en: {"中文文本":"对应的翻译文本",...}}
 */
export function cache_messages(data){
  cache(CACHE_KEY+'_messages', data);
  merge_cache_messages();
}

/**合并缓存的语言包
 */
export function merge_cache_messages(){
  let cache_messages = cache(CACHE_KEY+'_messages');
  if (!cache_messages || typeof cache_messages !== 'object') cache_messages = {};
  Object.keys(cache_messages).forEach(lang=>{
    if (!LANG_MAP[lang]) return;
    let old = messages[lang] || {};
    Object.assign(old, cache_messages[lang]);
    messages[lang] = old;
  })
}
merge_cache_messages();

export function get_lang(){
  return cache(CACHE_KEY) || 'zh_cn';
}

export function set_lang(lang){
  lang = lang.toLowerCase().replace('-','_');
  cache(CACHE_KEY, lang);
}

export function t(key, replace, lang){
  lang = lang || get_lang();
  let map = messages[lang] || {};
  let msg = map[key] || key;
  if (replace && typeof replace === 'object'){
    Object.keys(replace).forEach(k=>{
      msg = msg.replaceAll(`:${k}`, replace[k]);
    })
  }
  return msg;
}

/**返回或者设定缓存的金额配置列表
 * @param [data]
 * @returns {{symbol,rate}[]}
 */
export function cache_money_list(data){
  if (typeof data === 'undefined') return cache(CACHE_KEY+'_money_list') || [];
  cache(CACHE_KEY+'_money_list', data);
}


// 同时挂载到全局对象
if (typeof window !== 'undefined') {
  window['global_t'] = t
}

export default {
  t: t,
  install(vue) {
    // Vue 3+ 安装方式
    if (vue.config && vue.config.globalProperties){
      vue.config.globalProperties.$t = t;
    }
    // Vue 2 安装方式
    else if (vue.prototype) {
      vue.prototype.$t = t;
    }
  }
};
